class Event < ActiveRecord::Base
  belongs_to :course
  has_many :scheduled_items, :dependent=>:destroy
  has_many :teachings
  has_many :instructors, :through=>:teachings, :dependent=>:destroy
  validates_presence_of :event_name
  validates_presence_of :location
  validates_presence_of :start_time
  validates_presence_of :stop_time

  def days_time
    return days + ' ' + time
  end

  def time
    return format_time(start_time) + '-' + format_time(stop_time)
  end

  def days
    days = ''
    days += 'Su' if sunday
    days += 'M' if monday
    days += 'Tu' if tuesday
    days += 'W' if wednesday 
    days += 'Th' if thursday
    days += 'F' if friday
    days += 'Sa' if saturday
    return days
  end

  def conflicted_minutes_with(event)
    multiplier = 0
    multiplier += 1 if self.sunday and event.sunday
    multiplier += 1 if self.monday and event.monday
    multiplier += 1 if self.tuesday and event.tuesday
    multiplier += 1 if self.wednesday and event.wednesday
    multiplier += 1 if self.thursday and event.thursday
    multiplier += 1 if self.friday and event.friday
    multiplier += 1 if self.saturday and event.saturday

    maxStart = self.start_time
    maxStart = event.start_time if maxStart < event.start_time

    minStop = self.stop_time
    minStop = event.stop_time if minStop > event.stop_time

    timeDifference = minStop - maxStart
    timeDifference = 0 if timeDifference < 0

    return multiplier * timeDifference / 60
  end

  def expanded_title
    self.course.department + ' ' + self.course.course_number + ' ' + self.event_type + ' ' + self.section_number
  end

  def Event.is_valid_location(name)
    return count(:all, :conditions => {:location => name.upcase}) > 0
  end

  protected

  def format_time(time)
    hour = time.strftime("%I")
    # remove 0 prefix
    hour = hour[1, 1] if hour[0, 1] == '0'
    return hour + time.strftime(":%M%p")
  end

end
